import { fetchAlarmList, postAlarmControl, postAlarmHandling } from '@/api'
import { alarmMarkerLayer } from '@/shared/map/alarm'
import { useCarStore } from '@/stores/car'
import { ElMessage, useElMessage } from '@/stores/elMessage'
import { initWebSocket } from '@/utils'
import { Delete } from '@element-plus/icons-vue'
import { useVirtualList } from '@vueuse/core'
import dayjs from 'dayjs'
import {
  ElAlert,
  ElBadge,
  ElButton,
  ElCard,
  ElCol,
  ElImageViewer,
  ElOption,
  ElRow,
  ElScrollbar,
  ElSelect,
  ElTabPane,
  ElTabs,
  ElTooltip,
  type TabPaneName
} from 'element-plus'
import { Marker } from 'maptalks'
import type { Ref } from 'vue'
import { Fragment, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
export interface websocketData {
  id?: string
  type?: string
  message?: string
  code?: string
  longitude?: number
  latitude?: number
  heading?: number
  createTime?: string
  picPath?: string
  opencvRecordId?: number
  errorType?: number
}

// const notProcessData = ref<{
//   createTime?: string
//   picPath?: string
//   code?: string
//   id?: number
// } | null>(null)

// export const getNotProcessAlarm = async () => {
//   const res = await fetchNotProcessAlarm()
//   notProcessData.value = res.data
// }

// const messageBox = ref<any>(null)

function getTypeValue(type: string) {
  switch (type) {
    case '人员入侵':
      return 1
    case '铁丝网识别':
      return 2
    case '敬礼识别':
      return 3
  }
}

// export const handleAlarmAction = async (data: websocketData, mode: Mode) => {
//   let type
//   alarmMarkerLayer.clear()
//   if (data.message === '人员入侵') {
//     type = Type.PERSON
//   } else if (data.message === '铁丝网破孔') {
//     type = Type.HOLE
//   } else if (data.message === '无人值班') {
//     type = Type.SALUTE
//   }

//   await postAlarmHandling({ code: data.code, mode, type, opencvRecordId: data.opencvRecordId })
//   ElMessage({ type: 'success', message: i18n.global.t('cao-zuo-cheng-gong') })
//   messageBox.value.close()
//   alarmDialogVisible.value = false
// }

/**
 * 识别程序开关
 */
export const alarmStatus = ref<number>()
export const activeNoProcessAlarm = async () => {
  const carStore = useCarStore()
  await postAlarmControl({
    code: carStore.currentCar,
    status: alarmStatus.value,
    type: 1
  })
}

// 警报通知相关
export const useNotification = () => {
  // 通知列表抽屉是否可见
  // const notificationDrawerVisible = ref(true)

  // 通知列表数据
  const notifications: Ref<any[]> = ref([])

  // 国际化
  const { t } = useI18n()

  // 警报音频 dom 元素
  const alarmRef: Ref<HTMLMediaElement | undefined> = ref()

  // const wsData = ref<websocketData>({
  //   picPath: '',
  //   message: '',
  //   code: '',
  //   type: '',
  //   errorType: 0
  // })

  // 从 websocket 收到数据后
  function onMessage(e: any) {
    if (e.data !== 'heartbeat') {
      const data: websocketData = JSON.parse(e.data)
      const { longitude, latitude, heading } = data
      // const btn = resolveComponent('el-button')
      if (data.errorType === 2) {
        getTimeoutAlarm()
        // messageBox.value = ElNotification({
        //   type: 'warning',
        //   title: t('jing-bao'),
        //   dangerouslyUseHTMLString: true,
        //   duration: 300000,
        //   onClose: () => {
        //     alarmMarkerLayer.clear()
        //   },
        //   message: h('div', [
        //     h('div', { style: 'display: flex; justify-content: space-between;' }, [
        //       h('p', {}, message),
        //       h(
        //         btn,
        //         {
        //           style: 'color: #A0A0A0;cursor: pointer;',
        //           onClick: () => {
        //             handleAlarmAll(data)
        //           }
        //         },
        //         t('cha-kan-jing-bao-xiang-qing')
        //       )
        //     ]),
        //     h('div', { style: 'display: flex; justify-content: space-around;' }, [
        //       h(
        //         btn,
        //         {
        //           style: 'color: #ff931e;cursor: pointer;width: 6rem',
        //           onClick: () => {
        //             handleAlarmAction(data, Mode.PROCESS)
        //           }
        //         },
        //         t('shou-dong-chu-li')
        //       ),
        //       h(
        //         btn,
        //         {
        //           style: 'color: #409EFF;cursor: pointer;width: 6rem',
        //           onClick: () => {
        //             handleAlarmAction(data, Mode.NOT_PROCESS)
        //           }
        //         },
        //         t('bu-zuo-chu-li')
        //       )
        //     ])
        //   ])
        // })
        if (alarmRef.value && longitude && latitude) {
          alarmRef.value.play()
          // 声音设置
          alarmRef.value.volume = 1
          //警报闪烁
          handleAlarmEvent(longitude, latitude, heading!)
        }
      } else {
        // messageBox.value = ElNotification({
        //   type: 'warning',
        //   title: t('jing-bao'),
        //   dangerouslyUseHTMLString: true,
        //   duration: 300000,
        //   onClose: () => {},
        //   message: h('div', [
        //     h('div', { style: 'display: flex; justify-content: space-between;' }, [
        //       h('p', {}, message)
        //     ])
        //   ])
        // })
        if (alarmRef.value) {
          alarmRef.value.play()
          // 声音设置
          alarmRef.value.volume = 1
        }
      }
    }
  }

  // function handleAlarmAll(data: any) {
  //   alarmDialogVisible.value = true
  //   wsData.value = data
  // }

  //每次收到警报定位车辆
  function handleAlarmEvent(longitude: number, latitude: number, heading: number) {
    alarmMarkerLayer.clear()
    if (longitude && latitude) {
      const point = new Marker([longitude as number, latitude as number], {
        symbol: {
          markerType: 'triangle',
          markerFill: '#FF00F3',
          markerWidth: 14,
          markerHeight: 16,
          markerRotation: -Number(heading)
        }
      })
      alarmMarkerLayer.addGeometry(point)
      point.flash(200, 12)
    }
  }
  // websocket 实例
  let websocket: WebSocket | undefined
  // 是否显示 websocket 已断开的提示
  const isOpen = ref(false)

  onMounted(() => {
    getTimeoutAlarm()
    // getNotProcessAlarm()
    if (alarmRef.value) {
      alarmRef.value.load() // 预加载音频
    }
    websocket = initWebSocket('/websocket', {
      onmessage: onMessage,
      onopen: () => {
        isOpen.value = true
        ElMessage({
          type: 'success',
          message: t('jian-ting-jing-bao-lian-jie-cheng-gong')
        })
      },
      onclose: () => {
        isOpen.value = false
        ElMessage({
          type: 'warning',
          message: t('jian-ting-jing-bao-lian-jie-duan-kai')
        })
      },
      onerror: () => {
        isOpen.value = false
        ElMessage({
          type: 'error',
          message: t('jian-ting-jing-bao-lian-jie-cuo-wu')
        })
      }
    })
  })
  // 关闭页面同时关闭 websocket
  onBeforeUnmount(() => {
    websocket?.close()
  })

  // 虚拟滚动相关，防止数据过多滚动卡顿
  // https://vueuse.org/core/useVirtualList/#usevirtuallist
  const { list, containerProps, wrapperProps } = useVirtualList(notifications, {
    itemHeight: 125
  })

  const configList = [
    { id: 4, name: t('quan-bu') },
    { id: 0, name: t('wei-chu-li') },
    { id: 1, name: t('jin-xing-zhong') },
    { id: 2, name: t('yi-chu-li') },
    { id: 3, name: t('chao-shi-wei-chu-li') }
  ]

  const statusType = ref<number>(4)
  const unprocessedNumer = ref<number>(0)
  const ongoingList = ref<any[]>([])
  const processedList = ref<any[]>([])
  const notProcessedList = ref<any[]>([])
  const overdueNotProcessedList = ref<any[]>([])

  const getTimeoutAlarm = async () => {
    const res: { data: { list: any[]; total: number } } = await fetchAlarmList({
      page: 1,
      limit: 99999
    })
    // 使用 filter 方法分类数据
    notProcessedList.value = res.data.list.filter((item: any) => item.processingStatus === 0)
    ongoingList.value = res.data.list.filter((item: any) => item.processingStatus === 1)
    processedList.value = res.data.list.filter((item: any) => item.processingStatus === 2)
    overdueNotProcessedList.value = res.data.list.filter((item: any) => item.processingStatus === 3)

    switch (statusType.value) {
      case 0:
        notifications.value = notProcessedList.value
        break
      case 1:
        notifications.value = ongoingList.value
        break
      case 2:
        notifications.value = processedList.value
        break
      case 3:
        notifications.value = overdueNotProcessedList.value
        break
      default:
        notifications.value = res.data.list
    }
    unprocessedNumer.value = res.data.total
  }

  const handleTypeTabChange = async () => {
    await getTimeoutAlarm()
  }

  const previewSrcList = ref<string[]>([])

  const showPreviewImage = ref(false)

  const previewImage = (url: string) => {
    showPreviewImage.value = true
    previewSrcList.value = [url]
  }

  const TabNames = {
    FIRST: 'first',
    SECOND: 'second',
    THREE: 'three'
  }

  const currentTab = ref(TabNames.THREE)

  const handleTabChange = (name: TabPaneName) => {
    if (name === TabNames.FIRST) {
      getTimeoutAlarm()
    }
    // else if (name === TabNames.SECOND) {
    //   getNotProcessAlarm()
    // }
  }

  const elMessage = useElMessage()

  // 添加倒计时相关函数和状态
  const countdowns = ref<{ [key: string]: number }>({})
  const countdownTimers = ref<{ [key: string]: number }>({})

  const startCountdown = (id: string, createTime: string) => {
    const updateCountdown = () => {
      const start = dayjs(createTime)
      const deadline = start.add(5, 'minute')
      const now = dayjs()
      const diff = deadline.diff(now, 'second')

      if (diff <= 0) {
        clearInterval(countdownTimers.value[id])
        delete countdownTimers.value[id]
        countdowns.value[id] = 0
      } else {
        countdowns.value[id] = diff
      }
    }

    updateCountdown()

    countdownTimers.value[id] = window.setInterval(updateCountdown, 1000)
  }

  const getCountdown = (id: string, createTime: string) => {
    if (!(id in countdowns.value)) {
      startCountdown(id, createTime)
    }
    return countdowns.value[id] || 0
  }

  // 添加状态切换 API 函数
  const changeAlarmStatus = async (item: any, status: number) => {
    const carStore = useCarStore()
    await postAlarmHandling({
      code: carStore.currentCar,
      opencvRecordId: item.data.id,
      mode: status,
      type: getTypeValue(item.data.type)
    })
    ElMessage({
      type: 'success',
      message: t('cao-zuo-cheng-gong')
    })
    getTimeoutAlarm() // 刷新列表
  }

  // 警报抽屉组件
  const NotificationDrawer = () => (
    <div class="flex flex-col  h-[68vh]">
      <ElTabs v-model={currentTab.value} stretch={true} onTabChange={handleTabChange} type="card">
        <ElTabPane name={TabNames.THREE}>
          {{
            label: () => [
              <span>
                {t('cao-zuo')}
                <ElBadge
                  v-show={elMessage.elMessageNum}
                  value={elMessage.elMessageNum}
                  max={99}
                  type={'primary'}
                ></ElBadge>
              </span>
            ]
          }}
        </ElTabPane>
        <ElTabPane name={TabNames.FIRST}>
          {{
            label: () => [
              <span>
                {t('jing-bao')}
                <ElBadge
                  v-show={unprocessedNumer.value}
                  value={unprocessedNumer.value}
                  max={99}
                ></ElBadge>
              </span>
            ],
            default: () => [
              <ElTabs stretch={true} v-model={statusType.value} onTabChange={handleTypeTabChange}>
                {configList.map((item: any) => (
                  <ElTabPane key={item.id} label={item.name} name={item.id}></ElTabPane>
                ))}
              </ElTabs>
            ]
          }}
        </ElTabPane>
      </ElTabs>

      {currentTab.value === TabNames.FIRST && (
        <div
          class="overflow-hidden"
          ref={containerProps.ref}
          style={containerProps.style}
          onScroll={containerProps.onScroll}
        >
          <div {...wrapperProps.value}>
            {list.value.map((item) => (
              <ElCard key={item.data.id} class="mt-2 ">
                {{
                  default: () => (
                    <ElRow gutter={10}>
                      <ElCol span={4}>
                        <div class="flex items-center h-full truncate">{item.data.code}</div>
                      </ElCol>
                      <ElCol span={20}>
                        <ElRow gutter={10}>
                          <ElCol span={10} class="mb-2">
                            {/* 警报类型 */}
                            <div
                              class="cursor-pointer hover:text-gray-400 truncate"
                              onClick={() => previewImage(item.data.picPath)}
                            >
                              {item.data.type}
                            </div>
                          </ElCol>
                          <ElCol span={12}>
                            <ElTooltip
                              placement="top"
                              content={dayjs(item.data.createTime).format('YYYY-MM-DD HH:mm:ss')}
                            >
                              <div class="truncate text-right">
                                {dayjs(item.data.createTime).format('YYYY-MM-DD HH:mm:ss')}
                              </div>
                            </ElTooltip>
                          </ElCol>
                          <ElCol span={10}>
                            {/* 切换状态 */}
                            <ElSelect
                              v-model={item.data.processingStatus}
                              onChange={(value) => changeAlarmStatus(item, value)}
                              size="small"
                            >
                              {{
                                default: () => (
                                  <Fragment>
                                    <ElOption label={t('jin-xing-zhong')} value={1} />
                                    <ElOption label={t('yi-chu-li')} value={2} />
                                    <ElOption label={t('wei-chu-li')} value={0} disabled={true} />
                                    <ElOption
                                      label={t('chao-shi-wei-chu-li')}
                                      value={3}
                                      disabled={true}
                                    />
                                  </Fragment>
                                ),
                                label: () => {
                                  switch (item.data.processingStatus) {
                                    case 1:
                                      return (
                                        <span class="text-[var(--el-color-primary)]">
                                          {t('jin-xing-zhong')}
                                        </span>
                                      )
                                    case 2:
                                      return (
                                        <span class="text-[var(--el-color-success)]">
                                          {t('yi-chu-li')}
                                        </span>
                                      )
                                    case 0:
                                      return (
                                        <span class="text-[var(--el-color-warning)]">
                                          {t('wei-chu-li')}
                                        </span>
                                      )
                                    case 3:
                                      return (
                                        <span class="text-[var(--el-color-danger)]">
                                          {t('chao-shi-wei-chu-li')}
                                        </span>
                                      )
                                  }
                                }
                              }}
                            </ElSelect>
                          </ElCol>
                          <ElCol span={12}>
                            {/* 状态 */}
                            {item.data.updateTime ? (
                              <ElTooltip
                                placement="bottom"
                                content={dayjs(item.data.updateTime).format('YYYY-MM-DD HH:mm:ss')}
                              >
                                <div class="text-[var(--el-color-success)] truncate text-right">
                                  {dayjs(item.data.updateTime).format('YYYY-MM-DD HH:mm:ss')}
                                </div>
                              </ElTooltip>
                            ) : getCountdown(item.data.id, item.data.createTime) > 0 ? (
                              <div class="text-[var(--el-color-danger)] truncate text-right">
                                {Math.floor(getCountdown(item.data.id, item.data.dataTime) / 60)}:
                                {(getCountdown(item.data.id, item.data.dataTime) % 60)
                                  .toString()
                                  .padStart(2, '0')}
                              </div>
                            ) : (
                              <span class="text-[var(--el-color-danger)] truncate text-right">
                                {t('chao-shi-wei-chu-li')}
                              </span>
                            )}
                          </ElCol>
                        </ElRow>
                      </ElCol>
                    </ElRow>
                  )
                }}
              </ElCard>
            ))}
          </div>
        </div>
      )}

      {currentTab.value === TabNames.THREE && (
        <div class="overflow-hidden " ref={containerProps.ref} onScroll={containerProps.onScroll}>
          <div class="flex justify-end">
            <ElButton icon={Delete} circle onClick={elMessage.deleteElMessages}></ElButton>
          </div>
          <ElScrollbar height="100%">
            {[...elMessage.elMessages].reverse().map((elMessageItem, index) => (
              <ElAlert
                style="margin:5px 0"
                key={index}
                title={elMessageItem.message}
                type={elMessageItem.type}
                closable={false}
              />
            ))}
          </ElScrollbar>
        </div>
      )}
      {showPreviewImage.value && (
        <ElImageViewer
          onClose={() => (showPreviewImage.value = false)}
          urlList={previewSrcList.value}
        ></ElImageViewer>
      )}
    </div>
  )

  return {
    NotificationDrawer
  }
}
